package org.dromara.legal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.legal.domain.Consult;
import org.dromara.legal.domain.Revert;
import org.dromara.legal.domain.bo.ConsultBo;
import org.dromara.legal.domain.bo.RevertBo;
import org.dromara.legal.domain.vo.ConsultVo;
import org.dromara.legal.domain.vo.RevertVo;
import org.dromara.legal.mapper.ConsultMapper;
import org.dromara.legal.mapper.RevertMapper;
import org.dromara.legal.service.IConsultService;
import org.dromara.legal.service.IRevertService;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 咨询Service业务层处理
 *
 * @author zhuqingrun
 * @date 2024-10-15
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ConsultServiceImpl implements IConsultService {

    private final ConsultMapper baseMapper;

    private final IRevertService revertService;

    private final RevertMapper revertMapper;

    private final ISysUserService userService;

    /**
     * 查询咨询
     *
     * @param id 主键
     * @return 咨询
     */
    @Override
    public ConsultVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询咨询列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 咨询分页列表
     */
    @Override
    public TableDataInfo<ConsultVo> queryPageList(ConsultBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Consult> lqw = buildQueryWrapper(bo);
        Page<ConsultVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的咨询列表
     *
     * @param bo 查询条件
     * @return 咨询列表
     */
    @Override
    public List<ConsultVo> queryList(ConsultBo bo) {
        LambdaQueryWrapper<Consult> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Consult> buildQueryWrapper(ConsultBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Consult> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getLawyerId() != null, Consult::getLawyerId, bo.getLawyerId());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), Consult::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), Consult::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), Consult::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getImg()), Consult::getImg, bo.getImg());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Consult::getStatus, bo.getStatus());
        lqw.eq(ObjectUtil.isNotNull(bo.getCreateBy()), Consult::getCreateBy, bo.getCreateBy());
        lqw.orderByDesc(Consult::getCreateTime);
        return lqw;
    }

    /**
     * 新增咨询
     *
     * @param bo 咨询
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ConsultBo bo) {
        SysUserVo sysUserVo = userService.selectUserById(bo.getLawyerId());
        Consult add = MapstructUtils.convert(bo, Consult.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 发送链接给律师
            String templateId = "SMS_475125535";
            LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
            map.put("code", String.valueOf(add.getId()));
            SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
            SmsResponse smsResponse = smsBlend.sendMessage(sysUserVo.getPhonenumber(), templateId, map);
            if (!smsResponse.isSuccess()) {
                log.error("验证码短信发送异常 => {}", smsResponse);
            }
        }
        return flag;
    }

    /**
     * 修改咨询
     *
     * @param bo 咨询
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ConsultBo bo) {
        Consult update = MapstructUtils.convert(bo, Consult.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Consult entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除咨询信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            List<Revert> reverts = revertMapper.selectList(new LambdaQueryWrapper<Revert>().in(Revert::getConsultId, ids));
            if(reverts.size() > 0){
                throw new ServiceException("该咨询下存在回复，不能删除");
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public ConsultVo queryReply(ConsultBo bo) {
        ConsultVo consultVo = queryById(bo.getId());
        RevertBo revertBo= new RevertBo();
        revertBo.setConsultId(bo.getId());
        Map<String, Object> params = bo.getParams();
        // 设置查询已经审核通过的回复
        params.put("isQueryPass", true);
        revertBo.setParams(params);
        List<RevertVo> revertVos = revertService.queryList(revertBo);
        consultVo.setRevertVoList(revertVos);
        return consultVo;
    }
}
